/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.emove.modular.system.controller;

import cn.emove.config.properties.GunsProperties;
import cn.emove.core.common.annotion.BussinessLog;
import cn.emove.core.common.annotion.Permission;
import cn.emove.core.common.constant.Const;
import cn.emove.core.common.constant.dictmap.DeleteDict;
import cn.emove.core.common.constant.dictmap.UserDict;
import cn.emove.core.common.constant.factory.ConstantFactory;
import cn.emove.core.common.exception.BizExceptionEnum;
import cn.emove.core.common.page.LayuiPageFactory;
import cn.emove.core.log.LogObjectHolder;
import cn.emove.core.shiro.ShiroKit;
import cn.emove.core.shiro.ShiroUser;
import cn.emove.core.util.FilePortUtil;
import cn.emove.core.util.HttpUtil;
import cn.emove.modular.system.entity.Meter;
import cn.emove.modular.system.entity.User;
import cn.emove.modular.system.model.MeterDto;
import cn.emove.modular.system.model.MeterLogDto;
import cn.emove.modular.system.model.MeterReadingDto;
import cn.emove.modular.system.model.OrderDto;
import cn.emove.modular.system.service.DictService;
import cn.emove.modular.system.service.MeterReadingService;
import cn.emove.modular.system.service.MeterService;
import cn.emove.modular.system.service.UserService;
import cn.emove.modular.system.warpper.MeterReadingWrapper;
import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 系统管理员控制器
 *
 * @author fengshuonan
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping("/meter")
public class MeterController extends BaseController {

    private static String PREFIX = "/modular/system/meter/";

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private MeterService meterService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;


    /**
     * 跳转到查看管理员列表的页面
     *
     * @author jiaojiaxiang
     * @Date 2019/04/18 10:50
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "meter.html";
    }
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String meterNo,
                       @RequestParam(required = false) String shopName,
                       @RequestParam(required = false) String shopAdr,
                       @RequestParam(required = false) String meterStatus,
                       @RequestParam(required = false) String meterType,
                       @RequestParam(required = false) String meterModel) {


        Page<Map<String, Object>> meterReadings = meterService.selectMeters(null, meterNo,shopName, shopAdr,meterStatus,meterType,meterModel);
        Page wrapped = new MeterReadingWrapper(meterReadings).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);

    }


    /**
     * 跳转到抄表添加页面
     *
     * @author jiaojiaxiang
     *      * @Date 2019/04/18 10:50
     **/
    @RequestMapping(value = "/add")
    public String roleAdd() {
        return PREFIX + "meter_add.html";
    }

    /**
     * 查询商户下拉框
     * @return
     */
    @RequestMapping("/shopData")
    @ResponseBody
    public JSONObject selectShopData(){
        List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
        userList = userService.selectContractData(null);
        JSONObject ServerJson = new JSONObject();
        for (Map<String,Object> c : userList) {
            String shopNo = String.valueOf(c.get("shopNo"));
            if(shopNo.contains(",")){
                String[] shopNos = shopNo.split(",");
                for(String s : shopNos){
                    ServerJson.put(s, s);
                }
            }else {
                ServerJson.put(String.valueOf(c.get("shopNo")), c.get("shopNo"));
            }

        }
        return ServerJson;
    }
    /**
     * 查询派单的用户下拉框
     * @return
     */
    @RequestMapping("/contractParam")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Object shopParam(@RequestParam String shopNo) throws UnsupportedEncodingException {
        JSONObject json = new JSONObject();
        if("".equals(shopNo)){
            return json;
        }
        List<Map<String,Object>> contractList = userService.selectContractData(null);
        for(Map<String,Object> m : contractList){
            String[] shopNos = m.get("shopNo").toString().split(",");
            for(String s :shopNos){
                if(s.trim().equals(shopNo.trim())){
                    String shopName = m.get("shopName").toString();
                    String shopId = m.get("shopId").toString();
                    if(shopNo.length()>6){
                        json.put("shopAdr",shopNo.substring(6));
                    }else{
                        json.put("shopAdr",shopNo);
                    }
                    json.put("shopName",shopName);
                    json.put("shopId",shopId);

                }
            }
        }

        return json;
    }
    @RequestMapping(value = "/addSave")
    @BussinessLog(value = "保存", key = "shopId", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData addSave(MeterDto meterDto) {
        MeterDto data = meterService.selectDataExist(meterDto.getMeterNo());
        if(data!=null){
            throw new ServiceException(BizExceptionEnum.DATA_EXIST);
        }
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        String userId = shiroUser.getId();
        List<Map<String,Object>> contractList = userService.selectContractData(null);
        for(Map<String,Object> m : contractList){
            String[] shopNos = m.get("shopNo").toString().split(",");
            for(String s :shopNos){
                if(s.trim().equals(meterDto.getShopNo().trim())){
                    meterDto.setShopId(String.valueOf(m.get("shopId")));
                    meterDto.setShopName(String.valueOf(m.get("shopName")));
                    if(meterDto.getShopNo().trim().length()>6){
                        meterDto.setShopAdr(meterDto.getShopNo().trim().substring(6));

                    }else{
                        meterDto.setShopAdr(meterDto.getShopNo().trim());
                    }
                    meterDto.setShopNo(meterDto.getShopNo().trim());
                }
            }
        }

        meterDto.setStatus("1");
        meterDto.setMeterStatus("1");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        meterDto.setCreateTime(simpleDateFormat.format(new Date()));
        meterDto.setCreateUser(userId);
        meterDto.setDiscount(meterDto.getDiscount()+"%");
        Integer num = meterService.insertMeter(meterDto);
        MeterLogDto meterLogDto = new MeterLogDto();
        meterLogDto.setMeterId(String.valueOf(meterDto.getId()));
        meterLogDto.setMeterNo(meterDto.getMeterNo());
        meterLogDto.setOperatorId(userId);
        meterLogDto.setPosOperationDesc("新增一条表数据");
        meterLogDto.setStatus("1");
        meterLogDto.setCreateTime(simpleDateFormat.format(new Date()));
        meterLogDto.setCreateUser(userId);
        Integer logNum = meterService.insertMeterLog(meterLogDto);
        if(num>0&&logNum>0){
            return SUCCESS_TIP;
        }else {
            throw new ServiceException(BizExceptionEnum.OPERATION_ERROR);
        }

    }

    /**
     * 跳转至编辑页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/edit")
    public String meter_edit(@RequestParam int id,Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Meter meter = meterService.selectMeterById(id);
        String meterType = meter.getMeterType();
        if("1".equals(meterType)){
            meter.setMeterType("水表");
        }else if("2".equals(meterType)){
            meter.setMeterType("电表");
        }
        String energyMeterType = meter.getEnergyMeterType();
        if("1".equals(energyMeterType)){
            meter.setEnergyMeterType("实体卡充值表");
        }else if("2".equals(energyMeterType)){
            meter.setEnergyMeterType("远程充值表");
        }else if("3".equals(energyMeterType)){
            meter.setEnergyMeterType("机械表");
        }
        meter.setDiscount(meter.getDiscount().replace("%",""));
        model.addAllAttributes(BeanUtil.beanToMap(meter));
        LogObjectHolder.me().set(meter);
        return PREFIX + "meter_edit.html";
    }

    /**
     * 编辑保存
     * @param meterDto
     * @return
     */
    @RequestMapping(value = "/editSave")
    @BussinessLog(value = "编辑")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData editSave(MeterDto meterDto) {
        Meter meter = meterService.selectMeterById(meterDto.getId());
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        String userId = shiroUser.getId();
        List<Map<String,Object>> contractList = userService.selectContractData(meterDto.getShopNo());
        Integer num = 0;
        for(Map<String,Object> m : contractList){
            String[] shopNos = m.get("shopNo").toString().split(",");
            for(String s :shopNos){
                if(s.trim().equals(meterDto.getShopNo().trim())){
                    meterDto.setShopId(String.valueOf(m.get("shopId")));
                    meterDto.setShopName(String.valueOf(m.get("shopName")));
                    if(meterDto.getShopNo().trim().length()>6){
                        meterDto.setShopAdr(meterDto.getShopNo().trim().substring(6));

                    }else{
                        meterDto.setShopAdr(meterDto.getShopNo().trim());
                    }
                    meterDto.setShopNo(meterDto.getShopNo());
                    meterDto.setUpdateUser(userId);
                    meterDto.setDiscount(meterDto.getDiscount()+"%");
                    num = meterService.updateMeter(meterDto);
                }
            }
        }

        MeterLogDto meterLogDto = new MeterLogDto();
        meterLogDto.setMeterId(String.valueOf(meterDto.getId()));
        meterLogDto.setMeterNo(meter.getMeterNo());
        meterLogDto.setOperatorId(userId);
        StringBuffer sb = new StringBuffer();
        if(!meter.getShopNo().equals(meterDto.getShopNo())){
            sb.append("品牌名由'"+meter.getShopName()+"（"+meter.getShopNo()+"）'改为'"+meterDto.getShopName()+"（"+meterDto.getShopNo()+"）'。");
        }
        if(!meter.getTimesRate().equals(meterDto.getTimesRate())){
            sb.append("倍率由'"+meter.getTimesRate()+"'改为'"+meterDto.getTimesRate()+"'。");
        }
        if(!meter.getUnitPrice().equals(meterDto.getUnitPrice())){
            sb.append("单价由'"+meter.getUnitPrice()+"'改为'"+meterDto.getUnitPrice()+"'。");
        }
        if(meter.getLoseServiceCharge()!=null&&!meter.getLoseServiceCharge().equals(meterDto.getLoseServiceCharge())){
            String str = "";
            String loseStr = "";
            if("".equals(meter.getLoseServiceCharge())||meter.getLoseServiceCharge()==null){
                str = "空";
            }else{
                str = meter.getLoseServiceCharge();
            }
            if("".equals(meterDto.getLoseServiceCharge())||meterDto.getLoseServiceCharge()==null){
                loseStr = "空";
            }else{
                loseStr = meterDto.getLoseServiceCharge();
            }
            sb.append("服务费单价由'"+str+"'改为'"+loseStr+"'。");
        }
        if(!meter.getDiscount().equals(meterDto.getDiscount())){
            sb.append("折扣由'"+meter.getDiscount()+"'改为'"+meterDto.getDiscount()+"'。");
        }
        if(!meter.getMeterModel().equals(meterDto.getMeterModel())){
            sb.append("能源表模式由'"+ConstantFactory.me().getMeterModelName(meter.getMeterModel())+"'改为'"+ConstantFactory.me().getMeterModelName(meterDto.getMeterModel())+"'。");
        }
        if(meter.getShopNo().equals(meterDto.getShopNo())&&meter.getTimesRate().equals(meterDto.getTimesRate())&&meter.getUnitPrice().equals(meterDto.getUnitPrice())&&meter.getLoseServiceCharge()!=null&&meter.getLoseServiceCharge().equals(meterDto.getLoseServiceCharge())&&meter.getDiscount().equals(meterDto.getDiscount())&&meter.getMeterModel().equals(meterDto.getMeterModel())){
            sb.append("修改提交，什么都没有修改");
        }
        if("".equals(sb.toString())){
            sb.append("修改提交，什么都没有修改");
        }

        meterLogDto.setPosOperationDesc(sb.toString());
        meterLogDto.setStatus("1");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        meterLogDto.setCreateTime(simpleDateFormat.format(new Date()));
        meterLogDto.setCreateUser(userId);
        Integer logNum = meterService.insertMeterLog(meterLogDto);
        if(num>0&&logNum>0){
            return SUCCESS_TIP;
        }else {
            throw new ServiceException(BizExceptionEnum.OPERATION_ERROR);
        }

    }

    /**
     * 跳转至编辑起码页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/editStartMum")
    public String editStartMum(@RequestParam int id,Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Meter meter = meterService.selectMeterById(id);
        String meterType = meter.getMeterType();
        if("1".equals(meterType)){
            meter.setMeterType("水表");
        }else if("2".equals(meterType)){
            meter.setMeterType("电表");
        }
        String energyMeterType = meter.getEnergyMeterType();
        if("1".equals(energyMeterType)){
            meter.setEnergyMeterType("实体卡充值表");
        }else if("2".equals(energyMeterType)){
            meter.setEnergyMeterType("远程充值表");
        }else if("3".equals(energyMeterType)){
            meter.setEnergyMeterType("机械表");
        }
        model.addAllAttributes(BeanUtil.beanToMap(meter));
        LogObjectHolder.me().set(meter);
        return PREFIX + "meter_editStartMum.html";
    }

    /**
     * 编辑起码保存
     * @param meterDto
     * @return
     */
    @RequestMapping(value = "/editStartMumSave")
    @BussinessLog(value = "编辑起码")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData editStartMumSave(MeterDto meterDto) {
        Meter meter = meterService.selectMeterById(meterDto.getId());
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        String userId = shiroUser.getId();
        meterDto.setUpdateUser(userId);
        Integer num = meterService.updateMeter(meterDto);



        MeterLogDto meterLogDto = new MeterLogDto();
        meterLogDto.setMeterId(String.valueOf(meterDto.getId()));
        meterLogDto.setMeterNo(meter.getMeterNo());
        meterLogDto.setOperatorId(userId);
        StringBuffer sb = new StringBuffer();
        sb.append("起码值由'"+meter.getInitialNum()+"'改为'"+meterDto.getInitialNum()+"'。");
        sb.append("变更类型为："+meterDto.getChangeType()+"。");
        if(!"".equals(meterDto.getRemark())&&meterDto.getRemark()!=null){
            sb.append("备注："+meterDto.getRemark());
        }

        meterLogDto.setPosOperationDesc(sb.toString());
        meterLogDto.setStatus("1");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        meterLogDto.setCreateTime(simpleDateFormat.format(new Date()));
        meterLogDto.setCreateUser(userId);
        Integer logNum = meterService.insertMeterLog(meterLogDto);
        if(num>0&&logNum>0){
            return SUCCESS_TIP;
        }else {
            throw new ServiceException(BizExceptionEnum.OPERATION_ERROR);
        }

    }
    /**
     * 删除能源表
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @BussinessLog(value = "删除能源表", key = "id")
    public Object delete(@RequestParam Integer id) {

        this.meterService.logicRemoveById(id);

        return SUCCESS_TIP;
    }
    // 导入
    /**
     * 实现文件上传
     * */
    @RequestMapping(value = "/importData", method = RequestMethod.POST)
    @ResponseBody

    public JSONObject importTemplate(@RequestParam("file") MultipartFile file) {
        FileInputStream excelFileIn = null;
        JSONObject json = new JSONObject();
        int successNum = 0;
        int failNum = 0;
        int nullNum = 0;
        StringBuffer msg = new StringBuffer();
        if (!file.isEmpty()) {
            try {
                String filename = file.getOriginalFilename();
                boolean isExcel2003 = true;
                if (filename.matches("^.+\\.(?i)(xlsx)$")) {
                    isExcel2003 = false;
                }
                InputStream is = file.getInputStream();
                Workbook wb = null;
                if (isExcel2003) {
                    wb = new HSSFWorkbook(is);
                }else{
                    wb = new XSSFWorkbook(is);

                }
                String sheetName = wb.getSheetName(0);
                Sheet sheet = wb.getSheetAt(0);
                List<MeterDto> list = new ArrayList<MeterDto>();
                ShiroUser shiroUser = ShiroKit.getUserNotNull();
                String userId = shiroUser.getId();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                    if("能源表模板".equals(sheetName)){
                        Row row = sheet.getRow(r);
                        if (row == null) {
                            continue;
                        }
                        if(row.getCell(0)==null){
                            msg.append("第"+r+"行，能源表编号不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                        if(row.getCell(1)==null){
                            msg.append("第"+r+"行，单元号不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                        if(row.getCell(2)==null){
                            msg.append("第"+r+"行，能源表类型不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                        if(row.getCell(3)==null){
                            msg.append("第"+r+"行，能源表属性不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);

                        if(row.getCell(4)==null){
                            msg.append("第"+r+"行，倍率不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                        if(row.getCell(5)==null){
                            msg.append("第"+r+"行，单价不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);

                        if(row.getCell(7)==null){
                            msg.append("第"+r+"行，折扣不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);

                        if(row.getCell(8)==null){
                            msg.append("第"+r+"行，起码抄表数不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);

                        if(row.getCell(9)==null){
                            msg.append("第"+r+"行，能源表模式不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(9).setCellType(Cell.CELL_TYPE_STRING);



                        String meterNo = row.getCell(0).getStringCellValue();
                        if("".equals(meterNo)){
                            msg.append("第"+r+"行，能源表编号不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        if(meterNo.length()>20){
                            msg.append("第"+r+"行，能源表编号不能大于20位 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        MeterDto meter = meterService.selectDataExist(meterNo);
                        //新增标识
                        boolean newFlag = false;
                        if(meter==null){
                            meter = new MeterDto();
                            newFlag=true;
                        }else{
                            msg.append("第"+r+"行，能源表已存在，不能重复导入 <br/>");
                            failNum = failNum+1;
                            continue;
                        }

                    /*meter.setShopId(row.getCell(0).getStringCellValue());
                    meter.setShopName(row.getCell(1).getStringCellValue());*/
                        String shopData = row.getCell(1).getStringCellValue();
                        if("".equals(shopData)){
                            msg.append("第"+r+"行，单元号不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        meter.setMeterNo(meterNo);
                        meter.setShopNo(shopData);
                        if(shopData.trim().length()>6){
                            meter.setShopAdr(shopData.trim().substring(6));
                        }else{
                            meter.setShopAdr(shopData.trim());
                        }
                        boolean haveShopNoFlag = true;
                        List<Map<String,Object>> contractList = userService.selectContractData(null);
                        for(Map<String,Object> m : contractList){
                            String[] shopNos = m.get("shopNo").toString().split(",");
                            for(String s :shopNos){
                                if(s.trim().equals(shopData.trim())){
                                    meter.setShopId(String.valueOf(m.get("shopId")));
                                    meter.setShopName(String.valueOf(m.get("shopName")));
                                    haveShopNoFlag = false;
                                }
                            }
                        }
                        if(haveShopNoFlag){
                            msg.append("第"+r+"行，单元号出错，没有对应的单元号 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        String meterType = row.getCell(2).getStringCellValue();
                        if("".equals(meterType)){
                            msg.append("第"+r+"行，能源表类型不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        if("水表".equals(meterType)){
                            meter.setMeterType(1);
                        }else if("电表".equals(meterType)){
                            meter.setMeterType(2);
                        }else{
                            msg.append("第"+r+"行，能源表类型出错 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        String energyMeterType = row.getCell(3).getStringCellValue();
                        if("".equals(energyMeterType)){
                            msg.append("第"+r+"行，能源表属性不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        if("机械表".equals(energyMeterType)){
                            meter.setEnergyMeterType("3");
                        }else if("远程充值表".equals(energyMeterType)){
                            meter.setEnergyMeterType("2");
                        }else if("实体冲值表".equals(energyMeterType)){
                            meter.setEnergyMeterType("1");
                        }else{
                            msg.append("第"+r+"行，能源表属性出错 <br/>");
                            failNum = failNum+1;
                            continue;
                        }

                        //校验倍率、单价、起始值
                        String timesRate = row.getCell(4).getStringCellValue();
                        String unitPrice = row.getCell(5).getStringCellValue();
                        String discount = row.getCell(7).getStringCellValue();
                        String initialNum = row.getCell(8).getStringCellValue();
                        String modelType = row.getCell(9).getStringCellValue();
                        String timesRateMsg =isCheck(timesRate,1);
                        if(!"".equals(timesRateMsg)){
                            msg.append("第"+r+"行，倍率出错，"+timesRateMsg+" <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        String unitPriceMsg =isCheck(unitPrice,1);
                        if(!"".equals(unitPriceMsg)){
                            msg.append("第"+r+"行，单价出错，"+unitPriceMsg+" <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        if("商铺".equals(modelType)){
                            meter.setMeterModel("1");
                        }else if("广告位".equals(modelType)){
                            meter.setMeterModel("2");
                        }else if("临时场地".equals(modelType)){
                            meter.setMeterModel("3");
                        }else{
                            msg.append("第"+r+"行，能源表模式出错 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        if(row.getCell(6)!=null){
                            row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                            String loseServiceCharge = row.getCell(6).getStringCellValue();
                            if(!"".equals(loseServiceCharge)){
                                String loseServiceChargeMsg =isCheck(loseServiceCharge,1);
                                if(!"".equals(loseServiceChargeMsg)){
                                    msg.append("第"+r+"行，服务费单价出错，"+loseServiceChargeMsg+" <br/>");
                                    failNum = failNum+1;
                                    continue;
                                }
                                meter.setLoseServiceCharge(loseServiceCharge);
                            }
                        }

                        String discountMsg = isDiscount(discount);
                        if(!"".equals(discountMsg)){
                            msg.append("第"+r+"行，折扣出错，"+discountMsg+" <br/>");
                            failNum = failNum+1;
                            continue;
                        }

                        String initialNumMsg =isCheck(initialNum,0);
                        if(!"".equals(initialNumMsg)){
                            msg.append("第"+r+"行，起码出错，"+initialNumMsg+" <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        meter.setTimesRate(timesRate);
                        meter.setUnitPrice(unitPrice);
                        meter.setDiscount(discount+"%");
                        meter.setInitialNum(initialNum);

                        meter.setStatus("1");
                        meter.setCreateTime(simpleDateFormat.format(new Date()));
                        Integer num = meterService.insertOrUpdate(meter);
                        if(newFlag){
                            //日志表
                            MeterLogDto meterLogDto = new MeterLogDto();
                            meterLogDto.setMeterId(String.valueOf(meter.getId()));
                            meterLogDto.setMeterNo(meter.getMeterNo());
                            meterLogDto.setOperatorId(userId);
                            meterLogDto.setPosOperationDesc("新增一条表数据");
                            meterLogDto.setStatus("1");
                            meterLogDto.setCreateTime(simpleDateFormat.format(new Date()));
                            meterLogDto.setCreateUser(userId);
                            Integer logNum = meterService.insertMeterLog(meterLogDto);
                        }

                        successNum = successNum+1;
                        list.add(meter);
                    }else if("修改单价模板".equals(sheetName)){
                        Row row = sheet.getRow(r);
                        if (row == null) {
                            continue;
                        }
                        if(row.getCell(0)==null){
                            msg.append("第"+r+"行，能源表编号不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                        if(row.getCell(1)==null){
                            msg.append("第"+r+"行，单价不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        if(row.getCell(3)==null){
                            msg.append("第"+r+"行，折扣不能为空 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);

                        String meterNo = row.getCell(0).getStringCellValue();
                        MeterDto meter = meterService.selectDataExist(meterNo);
                        if(meter==null){
                            msg.append("第"+r+"行，电表不存在 <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);

                        String unitPrice = row.getCell(1).getStringCellValue();
                        String unitPriceMsg =isCheck(unitPrice,1);
                        if(!"".equals(unitPriceMsg)){
                            msg.append("第"+r+"行，单价出错，"+unitPriceMsg+" <br/>");
                            failNum = failNum+1;
                            continue;
                        }

                        if(row.getCell(2)!=null){
                            row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                            String loseServiceCharge = row.getCell(2).getStringCellValue();
                            if(!"".equals(loseServiceCharge)){
                                String loseServiceChargeMsg =isCheck(loseServiceCharge,1);
                                if(!"".equals(loseServiceChargeMsg)){
                                    msg.append("第"+r+"行，服务费单价出错，"+loseServiceChargeMsg+" <br/>");
                                    failNum = failNum+1;
                                    continue;
                                }
                                meter.setLoseServiceCharge(loseServiceCharge);
                            }

                        }
                        String discount = row.getCell(3).getStringCellValue();
                        String discountMsg =isDiscount(discount);
                        if(!"".equals(discountMsg)){
                            msg.append("第"+r+"行，折扣出错，"+discountMsg+" <br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        meter.setDiscount(discount+"%");
                        meter.setUnitPrice(unitPrice);
                        meter.setUpdateTime(simpleDateFormat.format(new Date()));
                        meter.setUpdateUser(userId);
                        Integer num = meterService.insertOrUpdate(meter);
                        successNum = successNum+1;
                    }else {
                        json.put("code",0);
                        json.put("msg","sheet名称不正确");
                    }
                }
                /*int num = 0;
                if(list.size()>0){
                    num = meterService.insertMeterBatch(list);
                }else{
                    json.put("code",0);
                    json.put("msg","没有可导入的数据");
                    return json;
                }*/
            } catch (IOException e) {
                json.put("code",0);
                json.put("msg","导入Excel版本格式有问题");
                return json;
            }
            json.put("code",1);
            json.put("successNum",successNum);
            json.put("failNum",failNum);
            json.put("nullNum",nullNum);
            json.put("msg",msg);
            return json;
        } else {
            json.put("code",0);
            json.put("msg","没有可读取的文件");
            return json;
        }
    }

    /**
     * 跳转至模板页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/templateDownload")
    public String templateDownload() {
        return PREFIX + "tempDownload.html";
    }
    /**
     * 模板下载
     *
     * @return
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(@RequestParam(required = false)  HttpServletRequest request, HttpServletResponse response,String tempType) throws Exception {

        //excel标题
        String[] title = {"能源表编号", "单元号", "能源表类型", "能源表属性(实体卡充值表、远程充值表、机械表)",  "倍率", "单价","服务费单价(可为空)","折扣(%)", "起码抄表数","能源表模式(商铺、广告位、临时场地)"};

        //excel文件名
        String fileName = "能源表模板.xls";

        //sheet名
        String sheetName = "能源表模板";

        String[][] content = new String[1][];;

        if("2".equals(tempType)){
            title = new String[]{"能源表编号", "单价", "服务费单价(可为空)","折扣(%)"};
            fileName = "修改单价模板.xls";
            sheetName = "修改单价模板";
            content[0] = new String[title.length];
            content[0][0] = "模板数据";
            content[0][1] = "1";
            content[0][2] = "";
            content[0][3] = "96.31";
        }else {
            content[0] = new String[title.length];
            content[0][0] = "模板数据";
            content[0][1] = "0210011F-TK06";
            content[0][2] = "电表";
            content[0][3] = "机械表";
            content[0][4] = "1";
            content[0][5] = "5";
            content[0][6] = "";
            content[0][7] = "95.12";
            content[0][8] = "0";
            content[0][9] = "广告位";
        }

//创建HSSFWorkbook
        HSSFWorkbook wb = FilePortUtil.getHSSFWorkbook(sheetName, title, content, null);

//响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public static boolean isNumericzidai(String str) {
        Pattern pattern = Pattern.compile("((^[1-9]\\d*)|^0)(\\.\\d{0,4}){0,1}$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    public static String isCheck(String value,int checkZero){
        StringBuffer sb =new StringBuffer();
        if("".equals(value)){
            sb.append("不能为空");
            return sb.toString();
        }
        if(!isNumericzidai(value)){
            sb.append("请输入正确数字;");
            return sb.toString();
        }
        int val = value.indexOf(".");
        if (val!=-1){
            if(value.substring(0,val).length()>5){
                sb.append("小数点前不能大于5;");
            }
            if(value.substring(val).length()==1){
                sb.append("'输入格式有误';");
            }
        }else{
            if (value.length() > 5) {
                sb.append("长度不能大于5;");
            }
        }
        if(checkZero==0){
            if(Double.valueOf(value)<0){
                sb.append("不能输入小于0;");
            }
        }else{
            if(Double.valueOf(value)<=0){
                sb.append("不能输入小于等于0;");
            }
        }
        return sb.toString();
    }
    public static String isDiscount(String str) {
        /*String lastStr = str.substring(str.length()-1);
        if(!"%".equals(lastStr)){
            return "折扣单价格式有误,最后需要输入%";
        }
        String value = str.substring(0,str.length()-1);*/
        Pattern pattern = Pattern.compile("^\\d\\.([1-9]{1,2}|[0-9][1-9])$|^[1-9]\\d{0,1}(\\.\\d{1,2}){0,1}$|^100(\\.0{1,2}){0,1}$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return "折扣格式有误";
        }
        return "";
    }
    /**
     * 跳转至审核页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/audit")
    public String meterReadingAudit(@RequestParam String ids,Model model) {
        if (ToolUtil.isEmpty(ids)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        ids = ids.substring(0,ids.lastIndexOf(","));
        model.addAttribute("ids", ids);
        LogObjectHolder.me().set(ids);
        return PREFIX + "meterReading_audit.html";
    }
    /**
     * 审核保存
     */
    @RequestMapping(value = "/auditSave")
    @ResponseBody
    public ResponseData audit(@RequestParam Integer flag,String ids,String remark) {
        String[] array = ids.split(",");
        String status = "";
        if(flag==0){
            status = "2";
        }else if(flag==1){
            status = "1";
        }
        Integer num = meterService.updateBatch(array, status, remark);
        if(num>0){
            return SUCCESS_TIP;
        }else{
            throw new ServiceException(BizExceptionEnum.OPERATION_ERROR);
        }

    }
    /**
     * 跳转至详情页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/meter_detail")
    public String ticketDetail(@RequestParam int id,Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("id", id);
        LogObjectHolder.me().set(id);
        return PREFIX + "meter_detail.html";
    }



    @RequestMapping("/meterDetailData/{id}")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Object meterDetailData(@PathVariable int id) {
        JSONObject jsonObject = new JSONObject();
        Meter meter = meterService.selectMeterById(id);
        List<MeterLogDto> meterLog = meterService.selectMeterLogByMeterId(id);
        for(int i=0;i<meterLog.size();i++){
            MeterLogDto log = meterLog.get(i);
            if(i==meterLog.size()-1){
                log.setRemark("新建");
            }else{
               log.setRemark("更改");
            }
            User user = userService.selectAPPUserById(log.getOperatorId());
            if (user==null) {
                user=userService.selectUserById(log.getOperatorId());
            }
            String createUserName = "";
            if (ToolUtil.isNotEmpty(user) && ToolUtil.isNotEmpty(user.getName())) {
                createUserName =  user.getName();
            }
            log.setCreateUser(createUserName);

            String roleId = user.getRoleId();
            String[] roles = roleId.split(",");
            if(isHave(roles,"2")){
               log.setRole("商户");
            }else if(isHave(roles,"3")){
                log.setRole("员工");
            }else{
                log.setRole("平台");
            }
        }
        JSONObject json = (JSONObject) JSONObject.toJSON(meter);
        json.put("meterSchedule", meterLog);
        if (meter != null) {
            jsonObject.put("code", 200);
            jsonObject.put("data", json);

            return jsonObject;
        }
        return null;
    }

    public static boolean isHave(String[] strs,String s){

        /*此方法有两个参数，第一个是要查找的字符串数组，第二个是要查找的字符或字符串*/
        int i = strs.length;
        while (i-- > 0){
            if(s.equals(strs[i])){
                return true;
            }
        }
        return false;
    }
}
